package org.example;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class BoundedStreamWordCount {
    public static void main(String[] args) throws Exception {
        // 创建执行环境
        StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> source = executionEnvironment.readTextFile("/Users/fengliulin/IdeaProjects/hadoop-learn/data-test/words.txt");

        // 讲每一行数据拆分
        SingleOutputStreamOperator<Tuple2<String, Long>> flatMapOperator = source.flatMap((String line, Collector<Tuple2<String, Long>> out) -> {
            String[] words = line.split(" ");
            for (String s : words) {
                out.collect(Tuple2.of(s, 1L));
            }
        }).returns(Types.TUPLE(Types.STRING, Types.LONG));

        // 按照word进行分组
        KeyedStream<Tuple2<String, Long>, String> keyBy = flatMapOperator.keyBy(value -> {
            return value.f0;
        });

        // 分组内进行聚合统计
        SingleOutputStreamOperator<Tuple2<String, Long>> sum = keyBy.sum(1);
        sum.print();

        executionEnvironment.execute();

    }
}

